package com.llf.Config;

import com.llf.Blog.Pojo.User;
import com.llf.Blog.ServiceImpl.UserServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

//自定义授权和认证
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserServiceImpl userService;
    //授权
    @Override

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        SimpleAuthorizationInfo info= new SimpleAuthorizationInfo();
       //拿到当前登录的对象
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();
        //设置用户权限
        info.addStringPermission(currentUser.getRole());
        return info;
    }


    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        //从数据库中查询验证
        UsernamePasswordToken usertoken = (UsernamePasswordToken) token;

        User user = userService.getUser(usertoken.getUsername());
        if (user == null){
            //说明这个用户不存在
            return null;
        }


        //密码认证
        //principal 将user放在第一个参数 可以将当前登录的对象传递到上面被访问
        return new SimpleAuthenticationInfo(user,user.getPassword(),"");
    }
}
